/*
 * mmap.c
 *
 *  Created on: 29/set/2014
 *      Author: root
 */


#include "mmap.h"
#include "commons.h"


void *mapFullFileShared(char *fullFileName, int * fileByteSize){
	void * mappedFile = NULL;
	int *fd = NULL;
	if(fullFileName==NULL){
		return NULL;
	}

	fd = openFile(fullFileName, READ, 1);
	if(*fd > 0){
		*fileByteSize = countFileBytes(fd);
		if((mappedFile = mmap(0,*fileByteSize ,PROT_READ,MAP_SHARED, *fd, 0)) == MAP_FAILED){
			notifyError(ERR_MMAP,1,0);
		}
		closeFile(fd);

	}
	free(fd);
	fd = NULL;
	return mappedFile;
}

int isAuthorizedInSecretsFile(char* mappedFile, int mappedFileSize, char *usr, char *pwd){
	char *mappedFileCopy = (char *)mappedFile;
//	char *mappedBase;
	char user[50], pass[25];
	int k, start;
	memset(user,'\0',50);
	memset(pass,'\0',25);
	k=0;
	while(k < mappedFileSize){
		//mappedBase = mappedFileCopy;
		if(mappedFileCopy[k] == '\n' && k < mappedFileSize)k++;
		start = k;
		while(mappedFileCopy[k]!=';' && k < mappedFileSize)k++;
		strncpy(user,&mappedFileCopy[start],k-start);
		k++;
		start = k;
		while(!isspace(mappedFileCopy[k]) && k < mappedFileSize)k++;
		strncpy(pass, &mappedFileCopy[start], k-start);
		if(strcasecmp(user,usr) == 0  && strcasecmp(pass,pwd) == 0){
			return 1;
		}
		memset(user,'\0',50);
		memset(pass,'\0',25);
	}
	return 0;
}

int isLocalUser(char* mappedFile, int mappedFileSize, char *usr){
	char *mappedFileCopy = (char *)mappedFile;
	char user[50];
	int start = 0;
	int k;
	char buf[128];
	memset(buf,'\0',128);
	memset(user,'\0',50);

	k = 0;
	while(k < mappedFileSize){
		start = k;
		while(mappedFileCopy[k]!=';' && k < mappedFileSize)k++;
		strncpy(user,&mappedFileCopy[start],k - start);
		k++;
		start = k;
		while(!isspace(mappedFileCopy[k]) && k < mappedFileSize)k++;
		if(mappedFileCopy[k]!='\0' && k < mappedFileSize)k++;
		if(strcasecmp(user,usr) == 0){
			return 1;
		}
		memset(user,'\0',50);
	}
	return 0;
}


int getMBoxListSize(char* mappedFile, int mappedFileSize){
	char *mappedFileCopy = (char *)mappedFile;
	int listSize = 0;
	int k = 0;

	while(k < mappedFileSize){
		if(isspace(mappedFileCopy[k]))
			listSize++;
		k++;
	}

	return listSize;
}


char** getUsers(char* mappedFile, int usrSize){
	//int readbytes=0,k=0;
	char *mappedFileCopy = (char *)mappedFile;
	char **users;
	int j, k;
	int start = 0;
	char buf[128];

	users = (char **)getMemory(usrSize,PCHAR_TYPE);
	memset(buf,'\0',128);

	k=0;
	j=0;
	while(k < usrSize){
		start = j;
		while(mappedFileCopy[j]!=';')j++;
		users[k] = (char *)getMemory(j-start+1,CHAR_TYPE);
		memset(users[k],'\0',j-start+1);
		strncpy(users[k],&mappedFileCopy[start],j-start);
		j++;
		start = j;
		while(!isspace(mappedFileCopy[j]))j++;
		if(mappedFileCopy[j]!='\0')j++;
		k++;
	}
	return users;
}

void closeMappedFile(void *mappedFile, int *fileByteSize){

	if((void*)munmap(mappedFile,*fileByteSize) == MAP_FAILED){
		notifyError(ERR_MUNMAP,1,0);
	}
}
